package cn.com.libertymutual.sp.biz;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import com.google.common.collect.Lists;

import cn.com.libertymutual.core.base.dto.ResponseBaseDto;
import cn.com.libertymutual.core.redis.util.RedisUtils;
import cn.com.libertymutual.core.util.Constants;
import cn.com.libertymutual.core.util.DateUtil;
import cn.com.libertymutual.core.util.StringUtil;
import cn.com.libertymutual.core.util.enums.CoreServiceEnum;
import cn.com.libertymutual.core.web.ServiceResult;
import cn.com.libertymutual.core.web.util.RequestUtils;
import cn.com.libertymutual.sp.bean.TbSpApplicant;
import cn.com.libertymutual.sp.bean.TbSpOrder;
import cn.com.libertymutual.sp.bean.TbSpUser;
import cn.com.libertymutual.sp.dao.ApplicantDao;
import cn.com.libertymutual.sp.dao.OrderDao;
import cn.com.libertymutual.sp.dao.UserDao;
import cn.com.libertymutual.sp.dto.QueryCommonResponseDto;
import cn.com.libertymutual.sp.dto.TPolicyDto;
import cn.com.libertymutual.sp.dto.TQueryPayInfoResponseDto;
import cn.com.libertymutual.sp.dto.TQueryPolicyRequstDto;
import cn.com.libertymutual.sp.dto.TQueryPolicyResponseDto;
import cn.com.libertymutual.sp.service.api.CaptchaService;
import cn.com.libertymutual.sp.service.api.ClaimsService;
import cn.com.libertymutual.sp.service.api.SmsService;
import cn.com.libertymutual.sys.bean.SysCodeNode;
import cn.com.libertymutual.sys.bean.SysServiceInfo;

/**
 * 业务逻辑类
 * @author AoYi
 *
 */
@Component
public class ClaimsBiz {
	private Logger log = LoggerFactory.getLogger(getClass());

	// 注入原子性业务逻辑
	@Resource
	private ClaimsService claimsService;
	@Resource
	private RedisUtils redis;
	@Resource
	private SmsService smsService;// 短信
	@Resource
	private CaptchaService captchaService;// 图形验证码
	@Autowired
	private UserDao userDao;
@Resource private OrderDao orderDao;
@Resource private ApplicantDao applicantDao;
@Resource RestTemplate restTemplate;

/**Remarks: 通过证件号码查询保单<br>
 * Version：1.0<br>
 * Author：AoYi<br>
 * DateTime：2017年11月7日下午3:19:22<br>
 * Project：liberty_sale_plat<br>
 * @param request
 * @param response
 * @param policyRequest
 * @return
 * @throws Exception
 */
public ServiceResult queryPolicysAuthen(HttpServletRequest request, HttpServletResponse response, 
		@RequestBody TQueryPolicyRequstDto policyRequest,String userCode)
		throws Exception {
	ServiceResult sr = new ServiceResult(Constants.SYS_ERROR_MSG, ServiceResult.STATE_EXCEPTION);
	try {
		
		//   用户信息查询
		boolean isValCode= false;
		
		if (StringUtil.isNotEmpty(policyRequest.getImgCode())) {
			isValCode = true;
			// 校验-图形码
			if (!captchaService.validationCaptcha(request, sr, redis, policyRequest.getImgCode())) {
				return sr;
			}
		}
		if(!"pay".equals(policyRequest.getValType())) {
			if (StringUtil.isNotEmpty(policyRequest.getVerCode())) {
				isValCode = true;
				// 校验-短信验证码
				if (!smsService.verifyCodeBool(request, sr, redis, policyRequest.getVerCode(), policyRequest.getMobileNo())) {
					return sr;
				}
			}	
		}
		if(!isValCode) {
			TbSpUser user =  userDao.findByUserCode(policyRequest.getUserCode());
			if(!policyRequest.getId().equals(user.getIdNumber())) {
				sr.setFail();
				sr.setResult("非法认证！");
				return sr;
			}
			if(!"pay".equals(policyRequest.getValType())) {
				if(!policyRequest.getMobileNo().equals(user.getMobile())) {
					sr.setFail();
					sr.setResult("非法认证！");
					return sr;				
				}
			}
		}else {
			if(!"pay".equals(policyRequest.getValType())) {
				ResponseBaseDto baseRs=this.validate(policyRequest);
				if(!baseRs.getStatus()){
					sr.setFail();
					sr.setResult("没有查询到该证件号和号码所对应的信息!");
					return sr;
				}				
			}
		}
		
		redis.setWithExpireTime(Constants.POLICYS_AUTHEN_ID_CAR+":"+request.getSession().getId(), policyRequest.getId(),3600);
		redis.setWithExpireTime(Constants.POLICYS_AUTHEN+":"+request.getSession().getId(),policyRequest,3600);
		Object id = redis.get(Constants.POLICYS_AUTHEN_ID_CAR+":"+request.getSession().getId());
		sr.setSuccess();
		
	} catch (Exception e) {
		log.warn("通过证件号码查询保单异常:" + e.toString());
	}
	return sr;
}

	public void destroy(HttpServletRequest request)
			throws Exception {
		redis.delete(Constants.POLICYS_AUTHEN_ID_CAR+":"+request.getSession().getId());
	
	}

	/**
	 * 查询第三方 验证接口
	 * @param requestPayDto
	 * @return
	 */
	public ResponseBaseDto validate( TQueryPolicyRequstDto requestPayDto){
		Map map = (Map) redis.get(Constants.SYS_SERVICE_INFO);
		SysServiceInfo sysServiceInfo = (SysServiceInfo) map.get(CoreServiceEnum.IDValidate_URL.getUrlKey());
		requestPayDto.setPartnerAccountCode(sysServiceInfo.getUserName());
		requestPayDto.setFlowId(sysServiceInfo.getUserName() + DateUtil.dateFromat(new Date(), DateUtil.DATE_TIME_PATTERN3) + new Date().getTime());
		HttpEntity<TQueryPolicyRequstDto> requestEntity = new HttpEntity<TQueryPolicyRequstDto>(requestPayDto, RequestUtils.genEncryptHttpHeaders(sysServiceInfo.getUserName(), sysServiceInfo.getPassword()));
		ResponseBaseDto response=new ResponseBaseDto();
		try {
			response= restTemplate.postForObject(sysServiceInfo.getUrl(), requestEntity, ResponseBaseDto.class);
		} catch (RestClientException e) {
			log.error(e.getMessage(), e);
			response.setStatus(false);
		}
		return response;
	}
	public ServiceResult findPolicys(HttpServletRequest request, HttpServletResponse response, 
			@RequestBody TQueryPolicyRequstDto policyRequest,String userCode)
			throws Exception {
		ServiceResult sr = new ServiceResult(Constants.SYS_ERROR_MSG, ServiceResult.STATE_EXCEPTION);
		try {
			Object id = redis.get(Constants.POLICYS_AUTHEN_ID_CAR+":"+request.getSession().getId());
			if(null==id){
				sr.setFail();
				return sr;
			}
//			userCode = "BS00000014";
//			TQueryPolicyRequstDto rePolicyRequest = new 
//			Object datePay = redis.get(Constants.POLICYS_AUTHEN+":"+request.getSession().getId());
//			if(null==datePay) {
//				sr.setFail();
//				sr.setResult("查询失败！");
//				return sr;
//			}else {
//				policyRequest=(TQueryPolicyRequstDto) datePay;
//			}
//			policyRequest.setId("350521199501257577");
			policyRequest.setId(id.toString());
			TQueryPolicyResponseDto policysResponseDto = claimsService.queryPolicys(policyRequest);
			List<TPolicyDto> resList= policysResponseDto.getPolicys();
			sr.setResult(policysResponseDto);
			sr.setSuccess();
			return sr;
//			if(StringUtil.isEmpty(userCode)){
//				sr.setResult(policysResponseDto);
//				sr.setSuccess();
//				return sr;
//			}
//			//查询本地有效保单
//			//userCode="bs1510632708854";
//			List<TbSpOrder> orderList=orderDao.findPolicyByUserId(userCode);
//			if(orderList!=null && orderList.size()>0){
//				if(resList==null){
//					resList=Lists.newArrayList();
//				}
//				for(TbSpOrder order:orderList){
//					//判断是否已经通过证件号查到了
//					boolean exists=false;
//					for(TPolicyDto map:resList){
//						exists=order.getPolicyNo().equals(map.getPolicyno());
//						if(exists){break;}
//					}
//					if(exists){continue;}
//					policyRequest.setId(order.getPolicyNo());
//					QueryCommonResponseDto statusResponseDto = claimsService.queryPolicyStatus(policyRequest);//查询状态
//					List<Map<String,Object>> statusList=statusResponseDto.getResList();
//					if(statusList!=null && statusList.size()>0 
//							&& ("1".equals(String.valueOf(statusList.get(0).get("status")))
//									||"0".equals(String.valueOf(statusList.get(0).get("status"))))){//在期,未生效
//						TPolicyDto newMap=new TPolicyDto();
//						newMap.setAppliname(order.getApplicantName());
//						newMap.setPolicyno(order.getPolicyNo());
//						newMap.setSumpremium(order.getAmount().toString());
//						newMap.setRiskcode( order.getRiskCode());
//						newMap.setStartdate( DateUtil.dateFromat(order.getStartDate()));
//						newMap.setEnddate( DateUtil.dateFromat(order.getEndDate()));
//						newMap.setRiskcname( order.getPlanName());
//						newMap.setStatus( String.valueOf(statusList.get(0).get("status")));
//						newMap.setAppliIdentifynumber( order.getIdNo());
//						//查询被保人信息
//						List<TbSpApplicant> insureds=applicantDao.findByOrderNo(order.getPolicyNo());
//						
//						newMap.setInsuredIdentifynumber( null==insureds||insureds.size()==0?null:insureds.get(0).getCarId());
//						newMap.setInsuredname( null==insureds||insureds.size()==0?null:insureds.get(0).getName());
//						resList.add(newMap);
//					}
//					
//				}
//				
//			}
//			sr.setResult(policysResponseDto);
//			sr.setSuccess();
//			return sr;
		} catch (Exception e) {
			log.warn("通过证件号码查询保单异常:" + e.toString());
		}
		return sr;
	}
	/**Remarks: 通过证件号码查询保单<br>
	 * Version：1.0<br>
	 * Author：AoYi<br>
	 * DateTime：2017年11月7日下午3:19:22<br>
	 * Project：liberty_sale_plat<br>
	 * @param request
	 * @param response
	 * @param policyRequest
	 * @return
	 * @throws Exception
	 */
	public ServiceResult queryPolicys(HttpServletRequest request, HttpServletResponse response, 
			@RequestBody TQueryPolicyRequstDto policyRequest,String userCode)
			throws Exception {
		ServiceResult sr = new ServiceResult(Constants.SYS_ERROR_MSG, ServiceResult.STATE_EXCEPTION);
		try {
			//黑名单控制
			Map<String, Map<String, SysCodeNode>> map = (Map<String, Map<String, SysCodeNode>>) redis.get(Constants.MAP_CODE);
			if(null!=map){
				Map<String, SysCodeNode> nodeMap=map.get("SPBlacklist");
				if(StringUtil.isNotEmpty(policyRequest.getId())
						&&policyRequest.getId().equals(nodeMap.get("911101135769049507"))){
					sr.setResult("该用户无权限！");
					return sr;
				}
			}
			if (StringUtil.isNotEmpty(policyRequest.getImgCode())) {
				// 校验-图形码
				if (!captchaService.validationCaptcha(request, sr, redis, policyRequest.getImgCode())) {
					return sr;
				}
			}
			if (StringUtil.isNotEmpty(policyRequest.getMobileNo())) {
				// 校验-短信验证码
				if (!smsService.verifyCodeBool(request, sr, redis, policyRequest.getVerCode(), policyRequest.getMobileNo())) {
					return sr;
				}
			}
			
			TQueryPolicyResponseDto policysResponseDto = claimsService.queryPolicys(policyRequest);
			/*List<TPolicyDto> resList= policysResponseDto.getPolicys();
			if(StringUtil.isEmpty(userCode)){
				sr.setResult(policysResponseDto);
				sr.setSuccess();
				return sr;
			}
			//查询本地有效保单  ：查询给别人投保的保单 （屏蔽查询别人保单，只能通过证件号查询）
			//userCode="bs1510632708854";
			List<TbSpOrder> orderList=orderDao.findPolicyByUserId(userCode);
			if(orderList!=null && orderList.size()>0){
				if(resList==null){
					resList=Lists.newArrayList();
				}
				for(TbSpOrder order:orderList){
					//判断是否已经通过证件号查到了
					boolean exists=false;
					for(TPolicyDto map:resList){
						exists=order.getPolicyNo().equals(map.getPolicyno());
						if(exists){break;}
					}
					if(exists){continue;}
					policyRequest.setId(order.getPolicyNo());
					QueryCommonResponseDto statusResponseDto = claimsService.queryPolicyStatus(policyRequest);//查询状态
					List<Map<String,Object>> statusList=statusResponseDto.getResList();
					if(statusList!=null && statusList.size()>0 
							&& ("1".equals(String.valueOf(statusList.get(0).get("status")))
									||"0".equals(String.valueOf(statusList.get(0).get("status"))))){//在期,未生效
						TPolicyDto newMap=new TPolicyDto();
						newMap.setAppliname(order.getApplicantName());
						newMap.setPolicyno(order.getPolicyNo());
						newMap.setSumpremium(order.getAmount().toString());
						newMap.setRiskcode( order.getRiskCode());
						newMap.setStartdate( DateUtil.dateFromat(order.getStartDate()));
						newMap.setEnddate( DateUtil.dateFromat(order.getEndDate()));
						newMap.setRiskcname( order.getPlanName());
						newMap.setStatus( String.valueOf(statusList.get(0).get("status")));
						newMap.setAppliIdentifynumber( order.getIdNo());
						//查询被保人信息
						List<TbSpApplicant> insureds=applicantDao.findByOrderNo(order.getOrderNo());
						
						newMap.setInsuredIdentifynumber( null==insureds||insureds.size()==0?null:insureds.get(0).getCarId());
						newMap.setInsuredname( null==insureds||insureds.size()==0?null:insureds.get(0).getName());
						resList.add(newMap);
					}
					
				}
				
			}*/
			sr.setResult(policysResponseDto);
			sr.setSuccess();
			return sr;
		} catch (Exception e) {
			log.warn("通过证件号码查询保单异常:" + e.toString());
		}
		return sr;
	}

	/**Remarks: 通过证件号码查询报案列表<br>
	 * Version：1.0<br>
	 * Author：AoYi<br>
	 * DateTime：2017年11月14日下午1:57:47<br>
	 * Project：liberty_sale_plat<br>
	 * @param request
	 * @param response
	 * @param policyRequest
	 * @return
	 * @throws Exception
	 */
	public ServiceResult queryReports(HttpServletRequest request, HttpServletResponse response, @RequestBody TQueryPolicyRequstDto policyRequest)
			throws Exception {
		ServiceResult sr = new ServiceResult(Constants.SYS_ERROR_MSG, ServiceResult.STATE_EXCEPTION);
		try {
//			if (StringUtil.isNotEmpty(policyRequest.getImgCode())) {
//				// 校验-图形码
//				if (!captchaService.validationCaptcha(request, sr, redis, policyRequest.getImgCode())) {
//					return sr;
//				}
//			}
//			if (StringUtil.isNotEmpty(policyRequest.getMobileNo())) {
//				// 校验-短信验证码
//				if (!smsService.verifyCodeBool(request, sr, redis, policyRequest.getVerCode(), policyRequest.getMobileNo())) {
//					return sr;
//				}
//			}
			Object datePay = redis.get(Constants.POLICYS_AUTHEN+":"+request.getSession().getId());
			if(null==datePay) {
				sr.setFail();
				sr.setResult("查询失败！");
				return sr;
			}else {
				policyRequest=(TQueryPolicyRequstDto) datePay;
			}
			return claimsService.queryReports(request, response, sr, policyRequest);
		} catch (Exception e) {
			log.warn("通过证件号码查询报案列表异常:" + e.toString());
		}
		return sr;
	}

	public ServiceResult queryProposal(HttpServletRequest request,
			HttpServletResponse response, TQueryPolicyRequstDto policyRequest,
			String userCode) {
		ServiceResult sr = new ServiceResult(Constants.SYS_ERROR_MSG, ServiceResult.STATE_EXCEPTION);
		try {
//			if (StringUtil.isNotEmpty(policyRequest.getImgCode())) {
//				// 校验-图形码
//				if (!captchaService.validationCaptcha(request, sr, redis, policyRequest.getImgCode())) {
//					return sr;
//				}
//			}
//			if (StringUtil.isNotEmpty(policyRequest.getMobileNo())) {
//				// 校验-短信验证码
//				if (!smsService.verifyCodeBool(request, sr, redis, policyRequest.getVerCode(), policyRequest.getMobileNo())) {
//					return sr;
//				}
//			}
		
			Object id = redis.get(Constants.POLICYS_AUTHEN_ID_CAR+":"+request.getSession().getId());
//			List<TbSpOrder> orderLists=orderDao.findNoPayId(id.toString(),"2");
//			TQueryPolicyResponseDto policysResponseDtoNopay = new TQueryPolicyResponseDto();
//			List<TPolicyDto> spOserList = new ArrayList<TPolicyDto>();
//			for(int i=0;i<orderLists.size();i++){
//				TPolicyDto newMap=new TPolicyDto();
//				TbSpOrder spOser = orderLists.get(i);
//				newMap.setProposalNo(spOser.getProposalNo());
//				newMap.setStatus("8");
//				newMap.setRiskcname(spOser.getProductName()+"-"+spOser.getPlanName());
//				newMap.setSumpremium(spOser.getAmount().toString());
//				newMap.setAppliname(spOser.getApplicantName());
//				newMap.setInsuredname("");
//				newMap.setStartdate(Long.toString(spOser.getStartDate().getTime()));
//				newMap.setEnddate(Long.toString(spOser.getEndDate().getTime()));
//				spOserList.add(newMap);
//			}
//			policysResponseDtoNopay.setPolicys(spOserList);
//			sr.setSuccess();
//			sr.setResult(policysResponseDtoNopay);
//			return sr;
			
			
			policyRequest.setId(id.toString());
			TQueryPolicyResponseDto policysResponseDto = claimsService.queryProposal(policyRequest);
			List<TPolicyDto> resList= policysResponseDto.getPolicys();
			
//			if(StringUtil.isEmpty(userCode)){
//				sr.setResult(policysResponseDto);
//				sr.setSuccess();
//				return sr;
//			}
			
			//查询本地有效保单
			//userCode="bs1510632708854";
//			List<TbSpOrder> orderList=orderDao.findProposalByUserId(userCode);
//			if(orderList!=null && orderList.size()>0){
//				if(resList==null){
//					resList=Lists.newArrayList();
//				}
//				for(TbSpOrder order:orderList){
//					//判断是否已经通过证件号查到了
//					boolean exists=false;
//					for(TPolicyDto map:resList){
//						exists=order.getProposalNo().equals(map.getProposalNo());
//						if(exists){break;}
//					}
//					if(exists){continue;}
//					policyRequest.setId(order.getProposalNo());
//					QueryCommonResponseDto statusResponseDto = claimsService.queryProposalStatus(policyRequest);//查询状态
//					List<Map<String,Object>> statusList=statusResponseDto.getResList();
//					if(statusList!=null && statusList.size()>0 && "8".equals(String.valueOf(statusList.get(0).get("underwriteflag")))
//							&& ("1".equals(String.valueOf(statusList.get(0).get("status")))
//									||"0".equals(String.valueOf(statusList.get(0).get("status"))))){//在期,未生效
//						TPolicyDto newMap=new TPolicyDto();
//						newMap.setAppliname(order.getApplicantName());
//						//newMap.setPolicyno(order.getPolicyNo());
//						newMap.setProposalNo(order.getProposalNo());
//						newMap.setSumpremium(order.getAmount().toString());
//						newMap.setRiskcode( order.getRiskCode());
//						newMap.setStartdate( DateUtil.dateFromat(order.getStartDate()));
//						newMap.setEnddate( DateUtil.dateFromat(order.getEndDate()));
//						newMap.setRiskcname( order.getPlanName());
//						newMap.setStatus( String.valueOf(statusList.get(0).get("status")));
//						newMap.setUnderwriteflag(String.valueOf(statusList.get(0).get("underwriteflag")));
//						newMap.setAppliIdentifynumber( order.getIdNo());
//						//查询被保人信息
//						List<TbSpApplicant> insureds=applicantDao.findByOrderNo(order.getOrderNo());
//						
//						newMap.setInsuredIdentifynumber( null==insureds||insureds.size()==0?null:insureds.get(0).getCarId());
//						newMap.setInsuredname( null==insureds||insureds.size()==0?null:insureds.get(0).getName());
//						resList.add(newMap);
//					}
//					
//				}
//				
//			}
			//筛选出待支付投保单
			//List<TPolicyDto> result=resList.stream().filter((TPolicyDto t) ->"8".equals(t.getUnderwriteflag())).collect(Collectors.toList());
//			policysResponseDto.setPolicys(result);
			
			sr.setResult(policysResponseDto);
			sr.setSuccess();
			return sr;
		} catch (Exception e) {
			log.warn("通过证件号码查询投保单异常:" + e.toString());
		}
		return sr;
	}

}
